package controller

import (
	"fmt"
	"gin/dao"
	"gin/model"
	"gin/tool"
	"github.com/gin-gonic/gin"
	"os"
	"path"
	"strconv"
	"strings"
	"sync"
	"time"
)

var wg sync.WaitGroup

type FileUploadController struct {
}

func (file *FileUploadController) Router(engine *gin.Engine) {
	//engine.GET("/indexList",index.IndexList)
	engine.POST("/api/upload/image", file.UploadImage)
}

//图片上传
func (file *FileUploadController) UploadImage(c *gin.Context) {
	f, _ := c.FormFile("image")
	//允许的图片后缀名
	allowExtMap := map[string]bool{
		".jpg":  true,
		".png":  true,
		".gif":  true,
		".jpeg": true,
	}
	sliceFileName := strings.Split(f.Filename, ".")
	extName := "." + sliceFileName[1]
	if _, ok := allowExtMap[extName]; !ok {
		fmt.Println("图片后缀名不合法")
	}
	//创建图片保存目录  static/upload/20200623
	dir := "static/upload/" + file.GetDay()
	if err := os.MkdirAll(dir, 0666); err != nil {
		fmt.Println("文件创建失败", dir, err)
	}
	//生成文件名称
	fileUnixName := strconv.FormatInt(file.GetUnixNano(), 10)
	saveDir := path.Join(dir, fileUnixName+extName)
	saveErr := c.SaveUploadedFile(f, saveDir)
	if saveErr != nil {
		fmt.Println(saveErr)
		tool.Error(c, "图片上传失败")
		return
	}
	config := tool.GetConfig()
	//fmt.Println(config.AppTitle)
	image := model.Image{
		Name:  "",
		Url:   "/" + saveDir,
		Path:  config.AppTitle + config.AppHost + "/" + saveDir,
		Ctime: int(time.Now().Unix()),
		Utime: int(time.Now().Unix()),
	}

	urlChan := make(chan string, 1) //创建一个管道
	imageDetailChan := make(chan *model.Image, 1)
	wg.Add(1) //开启一个协程
	go file.saveImageToDataBases(urlChan, image)

	wg.Add(1) //开启一个协程
	go func() {
		file.readImageDetail(urlChan, imageDetailChan)
	}()
	wg.Wait()
	//imageDetail := imageDao.FindWhereUrl( "/" + saveDir)
	tool.Success(c, <-imageDetailChan)
}

//将上传图片的url保存到数据库 并且写入管道
func (file *FileUploadController) saveImageToDataBases(urlChan chan string, image model.Image) {
	imageDao := dao.ImageDao{Orm: tool.DbEngine}
	_ = imageDao.Insert(image)
	urlChan <- image.Url
	close(urlChan)
	wg.Done()
}

//读取插入图片的详细信息
func (file *FileUploadController) readImageDetail(urlChan chan string, imageDetailChan chan *model.Image) {
	url := <-urlChan
	imageDao := dao.ImageDao{Orm: tool.DbEngine}
	imageDetail := imageDao.FindWhereUrl(url)
	wg.Done()
	imageDetailChan <- imageDetail
	//return imageDetail
}

//获取日期
func (file *FileUploadController) GetDay() string {
	template := "20060102"
	return time.Now().Format(template)
}

//获取当前纳秒时间戳
func (file *FileUploadController) GetUnixNano() int64 {
	return time.Now().UnixNano()
}

// 获取当前日期时间
func (file *FileUploadController) GetDate() string {
	template := "2006-01-02 15:04:05"
	return time.Now().Format(template)
}
